package com.cheneyjoo.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.cheneyjoo.config.RouteConfig;
import com.cheneyjoo.model.ResponseMessage;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.lang.reflect.InvocationTargetException;
import java.net.Socket;
import java.util.Optional;

public class ServerThread implements Runnable {
    private Socket socket = null;
    private BufferedReader in = null;
    private PrintStream out = null;
    public boolean isOnline = true;

    public ServerThread(Socket socket) throws IOException {
        this.socket = socket;
        in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
        out = new PrintStream(this.socket.getOutputStream());
    }

    @Override
    public void run() {
        try {
            while (isOnline) {
                String readLine = in.readLine();
                if("bye".equalsIgnoreCase(readLine)){
                    out.println("*server close*");
                    break;
                }
                JSONObject jsonObject= JSON.parseObject(readLine, Feature.OrderedField);
                ResponseMessage responseMessage = new RouteConfig().RegisterRoutes(jsonObject);
                System.out.println(readLine);
                System.out.println(JSON.toJSON(responseMessage));
                out.println(JSON.toJSON(responseMessage));
            }
        } catch (IOException | InstantiationException | InvocationTargetException | NoSuchMethodException | IllegalAccessException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (Optional.ofNullable(out).isPresent()) {
                System.out.println("输出流已经关闭");
                out.close();
            }
            if (Optional.ofNullable(in).isPresent()) {
                try {
                    System.out.println("输入流已经关闭");
                    in.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
            if (Optional.ofNullable(socket).isPresent()) {
                try {
                    System.out.println(socket.getInetAddress() + ":" + socket.getPort() + "socket已经关闭");
                    socket.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }

    public void close(){
        this.isOnline=false;
        out.println("*server close*");
    }
}
